#!/usr/bin/perl -w 

use Getopt::Std;

use vars qw/ %opt /;

# Default Config:

my $day_limit = 1.2;
my $night_limit = 3.0;
my $night_start = 23;
my $night_end = 7;

my $mysql_user = "";
my $mysql_pass = "";

# / Default Config

# no need to edit below this line

sub init() {
	use Getopt::Std;
        my $opt_string = 'hs:e:d:n:u:p:';
        getopts( "$opt_string", \%opt ) or usage();
        usage() if $opt{h};
}

sub usage() {
	print STDERR << "EOF";

    This program does...

    usage: $0 [-h] [-s hour] [-e hour] [-d limit] [-n limit] [-u user] [-p pass]

     -h        : this (help) message
     -s <h>    : night start hour (default $night_start)
     -e <h>    : night end hour (default $night_end)
     -d <limit>: set load trigger during day (default $day_limit)
     -n <limit>: set load trigger during night (default $night_limit)
     -u <user> : set mysql user (default "" - disabled)
     -p <pass> : set mysql password

    example: $0 -s 17 -e 8 -n 10 

EOF
	exit;
}

init();

$day_limit = $opt{'d'} if(defined $opt{'d'});
$night_limit = $opt{'n'} if(defined $opt{'n'});
$night_start = $opt{'s'} if(defined $opt{'s'});
$night_end = $opt{'e'} if(defined $opt{'e'});
$mysql_user = $opt{'u'} if(defined $opt{'u'});
$mysql_pass = $opt{'p'} if(defined $opt{'p'});

$uptime_out = `/usr/bin/uptime`;

if ($uptime_out =~ /load average: ([0-9\.]+),/) { 
	$load = $1;
} else {
	die("Failed to find load in '" . $uptime_out . "'\n");
}

my $limit = $day_limit;
$hour = `date '+%H'`;
if ($hour >= $night_start || $hour < $night_end) {
	$limit = $night_limit;
}

if ($load > $limit) {
	print("Load High Notification ($load)\n");
	print("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=\n\n");
	print("uptime:\n");
	print($uptime_out);
	print("\nmysql processlist:\n") unless ($mysql_user eq '');
	system("mysqladmin -u${mysql_user} -p${mysql_pass} processlist") unless($mysql_user eq '');
	print("\ntop:\n");
	system("top -b -n 1");
	print("\nps auxww:\n");
	system("ps auxww");
	print("\nvmstat:\n");
	system("vmstat 1 2 | tail -1");
	print("\niostat:\n");
	system("iostat");
	print("\nw:\n");
	system("w");
} # else load normal - stfu ..

